<#noparse>#!/bin/bash

# 初始化为空，必须通过参数传递，下面四个参数是保留参数，不能自定义参数中包含保留参数的变量名，并且必须全部设置。
APP_NAME=""
APP_VERSION=""
IMAGE_OWNER=""
IMAGE_CREATE_TIME=""

# 遍历所有参数 KEY=VALUE，赋值变量
for arg in "$@"
do
  case $arg in
    APP_NAME=*)
      APP_NAME="${arg#*=}"
      ;;
    APP_VERSION=*)
      APP_VERSION="${arg#*=}"
      ;;
    IMAGE_OWNER=*)
      IMAGE_OWNER="${arg#*=}"
      ;;
    IMAGE_CREATE_TIME=*)
      IMAGE_CREATE_TIME="${arg#*=}"
      ;;
    JAR_FILE=*)
      JAR_FILE="${arg#*=}"
      ;;
    *)
      echo "自定义参数: $arg"
      ;;
  esac
done

# 校验必传参数是否都已设置
if [[ -z "$APP_NAME" ]]; then
  echo "错误：必须传入 APP_NAME 参数"
  exit 1
fi

if [[ -z "$APP_VERSION" ]]; then
  echo "错误：必须传入 APP_VERSION 参数"
  exit 2
fi

if [[ -z "$IMAGE_OWNER" ]]; then
  echo "错误：必须传入 IMAGE_OWNER 参数"
  exit 3
fi

if [[ -z "$IMAGE_CREATE_TIME" ]]; then
  echo "错误：必须传入 IMAGE_CREATE_TIME 参数"
  exit 4
elif [[ ! "$IMAGE_CREATE_TIME" =~ ^[0-9]{14}$ ]]; then
  echo "错误：IMAGE_CREATE_TIME 格式不正确，必须为格式如 $(date +%Y%m%d%H%M%S) 的14位数字"
  exit 5
fi

# -------------------------------------------
# 设置构建【自定义】参数 ，并且打印变量值。先进行设置自定义参数，再设置保留参数，原因是防止保留参数被覆盖，不允许自定义参数中包含保留参数的变量名。
# -------------------------------------------

# -------------------------------------------
# 设置构建【保留】参数 ，并且打印变量值
# -------------------------------------------
if [[ -z "$JAR_FILE" ]]; then  # 如果JAR_FILE为空，则进行拼接
  JAR_FILE="${APP_NAME}-${APP_VERSION}.jar"
fi
IMAGE_TAG="${APP_NAME}:${APP_VERSION}"

echo "======================================="
echo "打印构建镜像【保留参数】："
cat <<EOF
打印构建镜像【保留参数】：
APP_NAME          = ${APP_NAME}
APP_VERSION       = ${APP_VERSION}
IMAGE_CREATE_TIME = ${IMAGE_CREATE_TIME}
IMAGE_OWNER       = ${IMAGE_OWNER}
JAR_FILE          = ${JAR_FILE}
IMAGE_TAG         = ${IMAGE_TAG}
EOF
echo "======================================="

#echo "======================================="
#echo "打印构建镜像【自定义参数】："
#echo "PARAM_NAME_A         = ${PARAM_NAME_A}"
#echo "PARAM_NAME_B         = ${PARAM_NAME_B}"
#echo "======================================="

docker volume create "${APP_NAME}"

docker build \
  --build-arg APP_NAME="${APP_NAME}" \
  --build-arg APP_VERSION="${APP_VERSION}" \
  --build-arg IMAGE_CREATE_TIME="${IMAGE_CREATE_TIME}" \
  --build-arg IMAGE_OWNER="${IMAGE_OWNER}" \
  --build-arg JAR_FILE="${JAR_FILE}" \
  -t "${IMAGE_TAG}" .
</#noparse>
